﻿using System;
using System.Diagnostics;

namespace ProjectClone.Tool
{
    /// <summary>
    /// Dos指令帮助类
    /// </summary>
    public class DosCommanHelper
    {
        #region 执行指令
        /// <summary>
        /// 执行指令
        /// </summary>
        /// <param name="command">指令</param>
        /// <param name="seconds">最长等待时间（秒）</param>
        /// <returns></returns>
        public static string ExeCommand(string command, int seconds = 10)
        {
            var output = "";
            if (string.IsNullOrWhiteSpace(command))
                return output;

            var process = new Process(); //创建进程对象
            var startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe", //设定需要执行的命令
                Arguments = "/C " + command, //“/C”表示执行完命令后马上退出
                UseShellExecute = false, //不使用系统外壳程序启动
                RedirectStandardInput = false, //不重定向输入
                RedirectStandardOutput = true, //重定向输出
                CreateNoWindow = true //不创建窗口
            };

            process.StartInfo = startInfo;
            try
            {
                if (process.Start())
                {
                    if (seconds == 0)
                    {
                        process.WaitForExit();
                    }
                    else
                    {
                        process.WaitForExit(seconds * 1000);
                    }
                    output = process.StandardOutput.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                process.Close();
            }
            return output;
        }
        #endregion
    }
}
